unit SmallStruct.Model.TSSModelFactory;

interface

uses SmallStruct.Core,
  SmallStruct.Core.TSSObjectFactory,
  SmallStruct.Model;

type
  TSSModelFactory = class(TSSObjectFactory, ISSModelFactory)
  private
    procedure InitDataModel(ADataModel: ISSDataModel);
  public
    function GetModel(const AModelName: string): ISSModel;
    procedure FreeModel(AModel: ISSModel);
  protected
    function GetModelConfiguration(const AModelName: string): ISSConfiguration;
  end;

implementation

uses
  SmallStruct.Configuration,
  SmallStruct.Model.TSSModel,
  SmallStruct.Model.TSSDataModel,
  SmallStruct.Database,
  SmallStruct.Model.TSSDynamicModel;

{ TSSModelFactory }

procedure TSSModelFactory.FreeModel(AModel: ISSModel);
begin
  AModel.ReleaseObjectInstance;
end;

function TSSModelFactory.GetModel(const AModelName: string): ISSModel;
var
  ModelClass: TSSModelClass;
  ModelContext: TSSModelContext;
  ModelConfiguration: ISSModelConfiguration;
begin
  ModelConfiguration := GetModelConfiguration(AModelName) as ISSModelConfiguration;

  case ModelConfiguration.GetType of
    ssmtDynamicModel:
      begin
        Result := TSSDynamicModel.Create(nil);
      end;
    ssmtDataModel:
      begin
        ModelClass := TSSModelClass(QueryClass(AModelName));
        Result := ModelClass.Create(nil);
        ModelContext := TSSDataModelContext.Create(nil);
        ModelContext.SetConfiguration(ModelConfiguration);
        Result.SetContext(ModelContext);
        InitDataModel(Result as ISSDataModel);
      end;
  end;
end;

function TSSModelFactory.GetModelConfiguration(const AModelName: string): ISSConfiguration;
begin
  Result := (GetSystemObject.GetConfigurationTable as ISSConfigurationTable).QueryModelConfiguration(AModelName);
end;

procedure TSSModelFactory.InitDataModel(ADataModel: ISSDataModel);
var
  DatabaseConnection: ISSDatabaseDriver;
  DatabaseConnectionName: string;
begin
  DatabaseConnectionName := (ADataModel.GetContext.GetConfiguration as ISSModelConfiguration).GetDatabaseConnectionName;
  DatabaseConnection := ((GetSystemObject.GetGlobalObjectTable as ISSObjectContainer).GetObject(SS_DATABASE_CONNECTION_FACTORY_NAME) as ISSDatabaseConnectionFactory).GetDatabaseConnection(DatabaseConnectionName);
  (ADataModel.GetContext.GetObjectInstance as TSSDataModelContext).SetDatabaseConnection(DatabaseConnection);

  ADataModel.InitObject;

  if ADataModel.IsAutoOpen then
    ADataModel.OpenDataModel('');
end;

end.
